local util = {}
local app = require 'app'
local game = app.game.running
local id_action_map = nil

function util.id2action(id)
    if not id_action_map then
        id_action_map = {}
        for action, v in pairs(game.config.card_type) do
            local card_type = v[1][1]
            local action_id = v[1][3]
            id_action_map[action_id] = action
        end
    end

    return id_action_map[id]
end

function util.action2id(action)
    if not game.config.card_type[action] then
        return -999
    end

    return game.config.card_type[action][1][3]
end

function util.action2type(action)
    if not game.config.card_type[action] then
        return ''
    end

    return game.config.card_type[action][1][1]
end

util.client2server_symbol =
{
    [1] = 'A',
    [2] = '2',
    [3] = '3',
    [4] = '4',
    [5] = '5',
    [6] = '6',
    [7] = '7',
    [8] = '8',
    [9] = '9',
    [10] = 'T',
    [11] = 'J',
    [12] = 'Q',
    [13] = 'K',
    [14] = 'B',
    [15] = 'R',
}

util.server_symbol2client = 
{
    ['A'] = 1,
    ['2'] = 2,
    ['3'] = 3,
    ['4'] = 4,
    ['5'] = 5,
    ['6'] = 6,
    ['7'] = 7,
    ['8'] = 8,
    ['9'] = 9,
    ['T'] = 10,
    ['J'] = 11,
    ['Q'] = 12,
    ['K'] = 13,
    ['B'] = 14,
    ['R'] = 15,
}

local sort_fun = function(p1, p2)
    return p1.client_weight < p2.client_weight
end

function util.cards2actionid(poker_data_t)
    table.sort(poker_data_t, sort_fun)

    local action = ""
    for _, poker_data in ipairs(poker_data_t) do
        action = action .. tostring(util.client2server_symbol[poker_data.client_value])
    end

    return util.action2id(action)
end

function util.action2client(action)
    ret = {}

    for i = 1, string.len(action) do
        table.insert(ret, util.server_symbol2client[string.sub(action, i, i)])
    end

    return ret
end

local poker_data = game.require 'pokers.poker_data'
function util.card_ids2action(card_ids)
    if #card_ids == 0 then
        return 'pass'
    end

    local poker_data_t = {}
    for _, card_id in ipairs(card_ids) do
        table.insert(poker_data_t, poker_data.new(card_id))
    end

    local action_id = util.cards2actionid(poker_data_t)
    return util.id2action(action_id)
end

return util